package com.oa.hyperion.api.v1;


import com.oa.hyperion.entity.Department;
import com.oa.hyperion.exception.http.NotFoundException;
import com.oa.hyperion.service.DepartmentService;
import com.oa.hyperion.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;


/**
 * 部门的controller
 */

//使用RestController =controller+ ResponseBody
@Api(tags={"部门操作接口"})
@RestController
@RequestMapping("/v1/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private EmployeeService employeeService;

    /**
     * 获取所有部门信息
     */
    @ApiOperation("获取所有部门信息,含leader的信息")
    @GetMapping("getAll")
    public List<Department> getAll(){
        return departmentService.getAllDepart();
    }



    /**
     * 添加新部门
     * RequestBody 允许参数是JSON格式
     *  指定部门领导后，其岗位也会变成对应部门的领导
     */
    @ApiOperation("添加新部门")
    @PostMapping("add")
    public String addDepartment(@RequestBody Department department){
                if(department==null) {
                    //传来的参数为空，抛出异常
                    throw new NotFoundException(404);
                }
                department.setStatus("y");

        if(departmentService.save(department)) {
                //获取部门领袖id
                   int leaderId= department.getHeader();
                   employeeService.updateLeader(leaderId);

            return "添加成功";
        }
        return "添加失败";
    }

    /**
     * 逻辑删除:部门
     *  将传入得 部门id 作为依据进行删除
     *  只修改status 状态，让其不显示
     *  添加成功：返回true
     *      否则返回 false
     */
    @ApiOperation("逻辑删除:部门")
    @DeleteMapping("delete/{id}")
    public String deleteDepartment(@PathVariable Integer id){
        Department depart=new Department();
        depart.setId(id);
        depart.setStatus("n");

        if(departmentService.updateById(depart)) {
            return "删除成功";
        }
        return "删除失败";
    }

    /**
     * 修改部门
     *
     * 可修改：name、header、status
     */
    @ApiOperation("修改部门")
    @PutMapping("update")
    public String updateDepartment(@RequestBody Department depart){

        //获取要修改的对象
        Department department=departmentService.getById(depart.getId());
        //有效性校验
        if(department==null){
            throw new NotFoundException(404);
        }

        if(depart.getName()!=null){
            department.setName(depart.getName());
        }

        if(depart.getHeader()!=null){
            department.setHeader(depart.getHeader());
        }

        if(depart.getStatus()!=null){
            department.setStatus(depart.getStatus());
        }

        if( departmentService.updateById(department)){
            return "修改成功";
        }
        return "修改失败";
    }


}
